//
//  BLScanViewController.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/5/22.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//

import UIKit

class BLScanViewController: UIViewController {
    
    var isShareURLStr = true
    
    private lazy var qrCodeAnimateImageView : UIImageView = {
        
        return UIImageView()
        
    }()
    
}

// MARK: - 主业务逻辑
extension BLScanViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setuoUI()
        qrCodeAnimateStart()
        setupQRCode()
    }
}


extension BLScanViewController{
    //设置UI界面
    func setuoUI() {
        
        //容器View
        let qrCodeView = UIView(frame:CGRectMake(0, 0, view.bounds.width * 0.5, view.bounds.width * 0.5))
        qrCodeView.center = view.center
        qrCodeView.contentMode = .ScaleToFill
        qrCodeView.clipsToBounds = true
        view.addSubview(qrCodeView)
        
        
        let textLabel = UILabel()
        textLabel.frame = qrCodeView.frame
        textLabel.text = "二维码扫描区域"
        
        
        //扫描区域
        let interestImageView = UIImageView(frame: qrCodeView.bounds)
        qrCodeView.addSubview(interestImageView)
        interestImageView.image = UIImage(named: "qrcode_border")
        
        //扫描动画View
        qrCodeAnimateImageView.frame = qrCodeView.bounds
        qrCodeView.addSubview(qrCodeAnimateImageView)
        qrCodeAnimateImageView.image = UIImage(named: "qrcode_scanline_qrcode")
        
    }
    
    func qrCodeAnimateStart() {
        self.qrCodeAnimateImageView.frame.origin.y = 0
        UIView.animateWithDuration(2.0) {
            self.qrCodeAnimateImageView.frame.origin.y = self.qrCodeAnimateImageView.frame.height
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.view.layoutIfNeeded()
        }
    }
    
}


extension BLScanViewController{
    //设置二维码识别
    func setupQRCode() {
        
        weak var weakSelf = self
        
        BLQRCode.shareQrCode.bl_scanQRCode(view, isDraw: true) { (resultStrs) in
            if weakSelf!.isShareURLStr {
                for str in resultStrs{
                    /// http://www.douyu.com/room/share/633019
                    if str =~ "http://www.douyu.com/room/share/" {
                        weakSelf!.isShareURLStr = false
                        let roomID = str.stringByReplacingOccurrencesOfString("http://www.douyu.com/room/share/", withString: "")
                        NSNotificationCenter.defaultCenter().postNotificationName(kPushLiveRoomNotification, object: roomID)
                    }
                }
            }
        }
    }
}